from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
import os


# 创建声明式基类
Base = declarative_base()

class Database:
    """通用数据库操作类，封装SQLite数据库连接和基本操作"""
    _engine = None
    _SessionLocal = None

    @classmethod
    def init_db(cls, db_path: str = "database.db"):
        """初始化数据库连接

        Args:
            db_path: SQLite数据库文件路径，默认为当前目录下的database.db
        """
        if cls._engine is None:
            cls._engine = create_engine(f"sqlite:///{db_path}")
            cls._SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=cls._engine)

    @classmethod
    def get_db(cls) -> Session:
        """获取数据库会话生成器

        Yields:
            db: 数据库会话对象
        """
        if cls._SessionLocal is None:
            raise Exception("Database not initialized. Call init_db() first.")
        db = cls._SessionLocal()
        try:
            yield db
        finally:
            db.close()

    @classmethod
    def create_tables(cls):
        """创建所有模型定义的表"""
        if cls._engine is None:
            raise Exception("Database not initialized. Call init_db() first.")
        Base.metadata.create_all(bind=cls._engine)